import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { InputC, PrimaryC, FormGroup, DATA_ENTRY, TableC, ModalC } from '../../../../comps';
import debounce from 'lodash/debounce';
import moment from 'moment';
import CardC from '../../Barra/comps/cardC';
import search from '../../../../assets/busi/workStation/Barra/search.png';
import styles from './index.less';
import MyModalC from '../../../Product/productManageNew/myModalC';
import accounting from 'accounting';
import bg from '../../../../assets/busi/workStation/Nonstandard/product_bg.png';

@connect(({ loading, nonStandardProductM, productManageM, fundManageNewM }) => ({
  loading,
  nonStandardProductM,
  productManageM,
  fundManageNewM,
}))
@Form.create()
export default class ProductComp extends PureComponent {
  constructor() {
    super();
    this.state = {
      state: 1,
      activeIndex: undefined, // 表格高亮行
      productCode: undefined,
      productSimpleName: '', // 选中产品简称
      columns: [
        { dataIndex: 'code', title: '产品代码', key: 'code' },
        {
          key: 'productSimpleName',
          dataIndex: 'productSimpleName',
          title: '产品名称',
          render: (text, record) => {
            if (text) {
              return <a onClick={() => this.selectRow(record, record.code)}>{text}</a>;
            } else {
              return '--';
            }
          },
        },
        { dataIndex: 'raiseMoney', title: '募集资金（亿元）', key: 'raiseMoney', width: 130, align: 'right' },
        { dataIndex: 'costPrice', title: '资金成本', key: 'costPrice', width: 100 },
        { dataIndex: 'startDate', title: '成立日', key: 'startDate', type: 'date' },
        { dataIndex: 'endDate', title: '到期日', key: 'endDate', type: 'date' },
      ],
      dataSource: [],
      productLength: 0,
      productList: [],
      pageSize: 10,
      current: 1,
      showContent: true, // 是否展开
      productNum: 0, // 募集资金不为空的总数
      visible: false, // 负债端管理弹窗是否可见
      operationVisible: false, // 资金调整弹窗
      record: undefined, // 当前行的数据
      producCodeModel: undefined, // 资金调整选中code
      amount2: undefined, // 限额
      rootId: '', // 选中产品时，记录rootId，用于查询组合设置数据
    };
    // 绑定lodash的防抖函数，避免频繁搜索的情况
    this.searchOnChange = debounce(this.searchOnChange, 500);
  }

  componentDidMount() {
    const { dispatch, type, info } = this.props;
    this.props.onRef(this);
    this.getList();
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { state, productCode } = this.props;
    if (nextProps.state !== state) {
      this.setState({
        state: nextProps.state,
      });
    }
  }

  // 刷新列表数据源
  refresh = () => {
    this.props.form.setFieldsValue({
      portfolio: '',
    });
    this.getList();
  };

  // 列表数据源
  getList = () => {
    const { dispatch, productCode } = this.props;
    let count = 0;
    dispatch({
      type: 'productManageM/getList',
      payload: {
        inveType: '0',
        currentPage: 1,
        numInPage: 9999,
      },
      callback: (res) => {
        if (res) {
          if (!productCode) {
            this.props?.productOnChange(res.dataSource[0]?.code);
          }
          res.dataSource.map((item) => {
            if (item.raiseMoney) count++;
          });
          this.setState(
            {
              dataSource: res.dataSource,
              productLength: res.dataSource ? res.dataSource.length : 0,
              productList: res.dataSource,
              rootId: res.dataSource[0].rootId,
              productNum: count,
            },
            () => {
              this.changePage(productCode ? productCode : res.dataSource[0]?.code);
            },
          );
        }
      },
    });
  };

  // 跳转页码
  changePage = (code) => {
    const { dataSource, pageSize } = this.state;
    let current, obj;
    dataSource.filter((item, index) => {
      if (item.code === code) {
        current = Math.floor((index + 1) / pageSize) + 1;
        obj = item;
      }
    });
    this.selectRow(obj, code);
    this.setState({
      current,
      productCode: code,
      productSimpleName: obj.productSimpleName,
    });
  };

  // 改变columns的样式
  changeColumns = (columns) => {
    const data = columns;
    if (data && data.length) {
      if (data[data.length - 1].title !== '操作') {
        data.push({
          key: 'operate',
          type: 'operate',
          title: '操作',
          width: 180,
          operates: [
            {
              title: '负债端管理',
              onClick: (record, index) => {
                // 获取组合代码下拉列表
                // 设置了产品code时，获取产品下的组合
                this.props.dispatch({
                  type: 'productAGroupM/getProductGroup',
                  payload: {
                    authority: 'read',
                    maatApi: false,
                    productCode: record.code,
                  },
                  callback: () => {},
                });
                this.setState({
                  visible: true,
                  record,
                });
              },
            },
            {
              title: '资金调整',
              onClick: (record, index) => {
                this.setState(
                  {
                    operationVisible: true,
                    record,
                    producCodeModel: record.rootId,
                  },
                  () => {
                    setTimeout(() => {
                      const {
                        form: { setFieldsValue },
                      } = this.productRef.props;
                      setFieldsValue({
                        productCode: `${record.code}-${record.productSimpleName}`,
                      });
                    }, 0);
                  },
                );
              },
            },
          ],
        });
      }
      data.map((item) => {
        if (item.key == 'raiseMoney') {
          item.render = (text, record) => {
            return text == null || text == undefined ? '--' : accounting.formatNumber(Number(text) / 100000000, 2);
          };
        }
        if (item.key == 'costPrice') {
          item.type = 'rate';
        }
      });
    }
    return data;
  };

  // 表格行点击事件
  selectRow = (record, index) => {
    this.props.dispatch({
      type: 'productManageM/getDetail',
      payload: {
        id: record.id,
      },
      callback: (res) => {
        if (res) {
          this.props.getModes(res.baseInfo?.modes);
        }
      },
    });
    this.setState(
      {
        activeIndex: index, // 获取点击行的索引
        productSimpleName: record.productSimpleName,
        productCode: record.code,
        rootId: record.rootId,
      },
      () => {
        this.props.productOnChange(record.code, record.productSimpleName);
        this.props.getRootId(record.rootId, record.gzCode);
      },
    );
  };

  // 表格高亮行
  setClassName = (record, index) => {
    return record.code === this.state.activeIndex ? 'selectRow' : '';
  };

  onExpendClick = (e) => {
    this.setState(
      {
        showContent: e,
      },
      () => {
        this.props.stateOnChange(e ? 1 : 2);
      },
    );
  };

  // 搜索框图标
  rightContent = () => {
    return (
      <div className='flotRight'>
        <img src={search}></img>
      </div>
    );
  };

  // 响应搜索框变化
  searchOnChange = (e) => {
    const { productList } = this.state;
    let newListDataSource = [];
    const searchData = e.target?.value;
    if (searchData == '' || searchData == null) {
      newListDataSource = productList;
    } else {
      newListDataSource = productList.filter((item) => {
        return item.productSimpleName.toString().includes(searchData) || item.code.toString().includes(searchData);
      });
    }
    this.setState({ dataSource: newListDataSource });
  };

  onTableChange = (pagination, filters, sorter) => {
    this.setState({
      current: pagination.current,
      pageSize: pagination.pageSize,
    });
  };

  // 组合切换
  codeChange = (e) => {
    const { record } = this.state;
    if (e) {
      const tempObj = {};
      tempObj.startDate = moment().format('YYYYMMDD');
      tempObj.userId = localStorage.getItem('antd-pro-userId');
      tempObj.search_NOTNULL_accountFlag = '1';
      tempObj.search_INLIST_portfolioCode = [e.key];
      this.props.dispatch({
        type: 'fundManageNewM/fetch',
        payload: {
          params: tempObj,
          current: 1,
          pageSize: 10,
        },
        callback: (res) => {
          if (res && res.length) {
            const {
              form: { setFieldsValue },
            } = this.productRef.props;
            this.setState({
              amount2: res[0].currentFundBalance,
            });
            setFieldsValue({
              amount2: res[0].currentFundBalance,
            });
          }
        },
      });
      record.portfolioCode = e.info.portfolioCode;
      record.portfolioName = e.info.portfolioName;
      this.setState({
        record,
      });
    }
  };

  submitModel = () => {
    const { record, amount2 } = this.state;
    const {
      form: { getFieldValue },
    } = this.productRef.props;
    const amount = `${getFieldValue('amount')}`;
    const type = getFieldValue('type');
    if (amount === '0') {
      message.error('请填写有效金额');
      return;
    }
    if (type == '1' && amount > amount2) {
      message.error('发生金额不能大于限额！');
      return;
    }
    this.props
      .dispatch({
        type: 'fundManageNewM/operation',
        payload: {
          code: record.portfolioCode,
          name: record.portfolioName,
          type,
          amount,
          operateBy: localStorage.getItem('antd-pro-userId'),
        },
      })
      .then((res) => {
        if (res && res.success) {
          message.success('资金操作成功');
          if (record.code == this.props.productCode) {
            this.props.fundChange();
          }
          this.setState({
            operationVisible: false,
            record: undefined,
            producCodeModel: undefined,
            amount2: undefined,
          });
        } else {
          message.error('资金操作失败');
        }
      });
  };

  render() {
    const { columns, dataSource, productLength, operationVisible, current, pageSize, productNum, record, visible, producCodeModel, state, showContent, productSimpleName, rootId } =
      this.state;
    const { loading, productCode } = this.props;
    const newColumns = this.changeColumns(columns);
    const modalProps = {
      destroyOnClose: true,
      visible: operationVisible,
      title: '资金调整',
      width: 900,
      okText: '提交',
      // okButtonProps: { loading: operationLoading },
      onOk: () => {
        this.submitModel();
      },
      onCancel: () => {
        this.setState({
          operationVisible: false,
          record: undefined,
          producCodeModel: undefined,
          amount2: undefined,
        });
      },
    };
    return (
      <div className={styles.mainCont}>
        {showContent ? (
          <div className={styles.openCont}>
            {/* 展开 */}
            <CardC title='非标产品' titleTip={`共${productLength}支产品，有${productNum}支产品提供了负债端信息`} type='11' showContent={true} onExpendClick={this.onExpendClick} />
            <div className={styles.searchCont}>
              <InputC
                form={this.props.form}
                dataIndex='portfolio'
                placeholder='请输入产品名称或代码进行模糊搜索'
                suffix={this.rightContent()}
                onChange={(e) => {
                  e.persist(); // 以异步方式访问事件属性，调用 event.persist()，阻止react合成事件，允许保留对事件的引用。
                  this.searchOnChange(e);
                }}
                style={{ width: '208px' }}
              />
              <div>
                <PrimaryC
                  title={'新增产品'}
                  onClick={() => {
                    this.props.changePage(2);
                  }}
                  style={{ marginRight: '16px' }}
                />
                <PrimaryC
                  title={'组合设置'}
                  onClick={() => {
                    this.props.changePage(3);
                  }}
                />
              </div>
            </div>
            <div className={styles.table}>
              <TableC
                columns={newColumns}
                dataSource={dataSource}
                rowClassName={this.setClassName} // 表格行点击高亮
                rowKey='id'
                loading={loading.effects['productManageM/getList']}
                scroll={{ X: 'max-content', y: 330 }}
                current={current}
                pageSize={pageSize}
                total={dataSource.length}
                onChange={this.onTableChange}
              />
            </div>
          </div>
        ) : (
          <div className={styles.closeCont} style={{ overflow: 'hidden' }}>
            <CardC title='非标产品' type='1' onExpendClick={this.onExpendClick} showContent={false} />
            {(state == 1 || state == 3 || state == 13 || state == 14) && (
              <div className={styles.content}>
                <div>
                  共<span className={styles.num}> {dataSource.length} </span>支产品，有<span className={styles.num}> {productNum} </span>支产品提供了负债端信息
                </div>
                {productSimpleName ? (
                  <div>
                    当前选中的产品为
                    <br />
                    <span className={styles.name}> {productSimpleName} </span>
                  </div>
                ) : (
                  ''
                )}
              </div>
            )}
            {(state == 11 || state == 12) && (
              <div className={styles.content}>
                <div>
                  共<span className={styles.num}> {dataSource.length} </span>支产品
                </div>
                <div>
                  有<span className={styles.num}> {productNum} </span>支产品提供了
                  <br />
                  负债端信息
                </div>
                {productSimpleName ? (
                  <div>
                    当前选中的产品为
                    <br />
                    <span className={styles.name}> {productSimpleName} </span>
                  </div>
                ) : (
                  ''
                )}
              </div>
            )}
            <div className={styles.closeContbg}>
              <img src={bg} />
            </div>
          </div>
        )}

        {visible && (
          <MyModalC
            visible={visible}
            detailData={record || {}}
            onCancel={(e) => {
              this.setState({
                visible: false,
                record: undefined,
              });
              if (e) {
                this.getList();
              }
            }}
          />
        )}
        <ModalC {...modalProps}>
          <div>
            <FormGroup
              dataSource={[
                {
                  dataIndex: 'productCode',
                  title: '产品',
                  type: DATA_ENTRY.PRODUCTLIST,
                  allowClear: true,
                  onRef: (ref) => (this.productRef = ref),
                  rules: [[{ required: true, message: '请选择产品!' }]],
                  span: 12,
                  disabled: true,
                },
                {
                  title: '组合',
                  dataIndex: 'code',
                  type: DATA_ENTRY.PRODUCTGROUPTREE,
                  ralation: true,
                  productId: producCodeModel,
                  allowClear: true,
                  multiple: false,
                  onChange: (e) => this.codeChange(e),
                  rules: [{ required: true, message: '请选择' }],
                  span: 12,
                },
                {
                  title: '币种',
                  dataIndex: 'moneyType',
                  type: DATA_ENTRY.INPUT,
                  initialValue: '人民币',
                  disabled: true,
                },

                {
                  dataIndex: 'type',
                  type: DATA_ENTRY.SELECT,
                  title: '调整方向',
                  initialValue: '0',
                  placeholder: '请选择',
                  dataSource: [
                    { value: '0', title: '资金增加' },
                    { value: '1', title: '资金减少' },
                  ],
                  onChange: this.changeType,
                  span: 12,
                },
                {
                  title: '限额(元)',
                  dataIndex: 'amount2',
                  type: DATA_ENTRY.INPUTNUMBER,
                  min: 0,
                  precision: 2,
                  splitStyle: true,
                  initialValue: undefined,
                  disabled: true,
                  span: 12,
                },
                {
                  title: '发生金额',
                  dataIndex: 'amount',
                  type: DATA_ENTRY.INPUTNUMBER,
                  min: 0,
                  precision: 2,
                  splitStyle: true,
                  rules: [{ required: true, message: '请填写发生金额' }],
                  span: 12,
                },
                {
                  dataIndex: 'remark',
                  title: '备注',
                  type: DATA_ENTRY.INPUT,
                  showTextArea: true,
                  span: 24,
                  controlLabelSpan: 4,
                },
              ]}
              autoLayout={false}
            />
          </div>
        </ModalC>
      </div>
    );
  }
}
